package com.software.levelupandroid.entity;

/**
 * @Description 自定义的Resource类来封装数据、错误和加载状态
 * @Author LiangYaJie
 * @CreateTime 2024年05月24日 15:20:34
 */
public class Resource<T> {
    private T data;
    private String errorMessage;
    private boolean isLoading;

    public Resource() {
    }

    private Resource(T data, String errorMessage, boolean isLoading) {
        this.data = data;
        this.errorMessage = errorMessage;
        this.isLoading = isLoading;
    }

    //加载中状态
    public static <T> Resource<T> loading(T data){
        return new Resource<>(data, null, true);
    }

    //成功状态
    public static <T> Resource<T> success(T data){
        return new Resource<>(data, null, false);
    }

    //错误状态
    public static <T> Resource<T> failure(String msg, T data){
        return new Resource<>(data, msg, false);
    }

    //状态修改
    public void onSuccess(T data){
        this.data = data;
        this.errorMessage = null;
        this.isLoading = false;
    }
    public void onFailure(String msg, T data){
        this.data = data;
        this.errorMessage = msg;
        this.isLoading = false;
    }
    public void onLoading(T data){
        this.data = data;
        this.errorMessage = null;
        this.isLoading = true;
    }

    //状态判断
    public boolean isLoading(){
        return isLoading;
    }
    public boolean isSuccess(){
        return errorMessage == null && !isLoading;
    }
    public boolean isFailure(){
        return errorMessage != null && !isLoading;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public void setLoading(boolean loading) {
        isLoading = loading;
    }
}
